<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" style="margin-top: 20px">
      <template #coordinate>
        <div class="flex gap-10px">
          X
          <Input readonly v-model:value="dataRef.x" />
          Y
          <Input readonly v-model:value="dataRef.y" />
        </div>
      </template>
      <template #type="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px">
            <Select :options="typeOptions" v-model:value="model[field]" style="width: 120px" />
            <Select
              style="flex: 1"
              :options="formGetFieldsData"
              showSearch
              optionFilterProp="label"
              v-model:value="dataRef.fieldName"
              v-if="model[field] === 'field'"
              @change="handleFieldName"
            />
            <Select
              style="flex: 1"
              :options="formGetBtnsData"
              showSearch
              optionFilterProp="label"
              v-model:value="dataRef.btnName"
              v-if="model[field] === 'button'"
              @change="handleBtnName"
            />
            <Input style="flex: 1" v-model:value="dataRef.imgUrl" v-if="model[field] === 'img'" />
          </div>
        </FormItemRest>
      </template>
      <template #fontIcon="{ model, field }">
        <Select
          v-model:value="model[field]"
          placeholder="请选择"
          style="width: 100%"
          showSearch
          optionFilterProp="label"
          :filter-option="filterOption"
        >
          <SelectOption
            v-for="item in flowMacroGetFontAwesomeList"
            :value="item.value"
            :key="item.value"
          >
            <i :class="`fa ${item.label}`"></i> {{ item.label }}
          </SelectOption>
        </Select>
      </template>
      <template #align="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px items-center">
            <Select style="flex: 1" :options="alignOptions" v-model:value="model[field]" />
            padding
            <InputNumber style="flex: 1" v-model:value="dataRef['paddingTop']" addon-after="上" />
            <InputNumber style="flex: 1" v-model:value="dataRef['paddingRight']" addon-after="右" />
            <InputNumber
              style="flex: 1"
              v-model:value="dataRef['paddingBottom']"
              addon-after="下"
            />
            <InputNumber style="flex: 1" v-model:value="dataRef['paddingLeft']" addon-after="左" />
          </div>
        </FormItemRest>
      </template>
      <template #fontSize="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px">
            <InputNumber style="flex: 1" v-model:value="model[field]" />
            <Checkbox v-model:checked="dataRef.isBold">是否加粗</Checkbox>
          </div>
        </FormItemRest>
      </template>
      <template #bgImgUrl="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px">
            <Input style="flex: 1" v-model:value="model[field]" />
            <a-button @click="model[field] = ''">清空</a-button>
            <Image
              :src="
                model[field]
                  ? model[field].startsWith('/')
                    ? serverInfo.rootPath + model[field]
                    : serverInfo.rootPath + '/' + model[field]
                  : ''
              "
              width="32px"
            />
          </div>
        </FormItemRest>
      </template>
      <template #fontColor="{ model, field }">
        <FormItemRest>
          <div class="flex items-center gap-5px">
            <ColorPicker format="rgba" v-model:value="model[field]" />
            <a-button type="text" @click="model[field] = '#c9c9c9'">清空</a-button>
          </div>
        </FormItemRest>
      </template>
      <template #bgColor="{ model, field }">
        <FormItemRest>
          <div class="flex items-center gap-5px">
            <ColorPicker format="rgba" v-model:value="model[field]" />
            <a-button type="text" @click="model[field] = '#fff'">清空</a-button>
          </div>
        </FormItemRest>
      </template>
      <template #bgImg>
        <Upload
          :file-list="fileList"
          :before-upload="beforeUpload"
          @remove="handleRemove"
          :maxCount="1"
          @change="handleChange"
        >
          <a-button>
            <UploadOutlined />
            选择文件
          </a-button>
        </Upload>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import {
    Input,
    InputNumber,
    Select,
    Checkbox,
    Form,
    UploadProps,
    Upload,
    Image,
  } from 'ant-design-vue';
  import { formSchema, typeOptions, alignOptions, setData } from './listComponentModal.data';
  import { getFormGetFields, getFlowMacroGetFontAwesome } from '/@/api/flowManage/flowManage';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { isArray } from '/@/utils/is';
  import { useUserStore } from '/@/store/modules/user';
  import {
    getVisualUpdatePageList,
    getVisualUpdatePageMobileList,
    getVisualListColOperateCustomBtns,
  } from '/@/api/module/module';
  import { cloneDeep } from 'lodash-es';
  import { ColorPicker } from '/@/components/ColorPicker';

  export default defineComponent({
    name: 'ListComponentModal',
    components: {
      BasicModal,
      BasicForm,
      Input,
      Select,
      FormItemRest: Form.ItemRest,
      Checkbox,
      InputNumber,
      Upload,
      UploadOutlined,
      SelectOption: Select.Option,
      Image,
      ColorPicker,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const userStore = useUserStore();
      const serverInfo = userStore.getServerInfo;
      const { createMessage } = useMessage();
      const isUpdate = ref(false);
      const dataRef = ref<Recordable>({});
      const formCode = ref('');
      const moduleCode = ref('');
      //phone column 6 , pc column 12
      const column = ref(6);
      const type = ref('phone');
      const currentItemIndex = ref(-1);

      const fileList = ref<UploadProps['fileList']>([]);
      const item = ref<Recordable>({});
      const layoutList = ref<Recordable[]>([]);
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '800px' });
        formCode.value = data?.formCode;
        moduleCode.value = data?.moduleCode;
        layoutList.value = cloneDeep(data?.layoutList || []);
        currentItemIndex.value = data?.currentItemIndex;
        item.value = data?.record;
        column.value = data?.column;
        type.value = data?.type;
        fileList.value = [];
        resetFields();
        getFormGetFieldsData();
        getFormGetBtnsData();
        try {
          dataRef.value = {
            ...item.value.record,
            y: item.value.y,
            isBold: item.value.isBold == 'true' || item.value.isBold == true ? true : false,
          };
          isUpdate.value = data?.isUpdate;
          setFieldsValue({ ...dataRef.value });
        } catch (err) {
          console.error(err);
        }
      });
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const getTitle = computed(() => (isUpdate.value ? '编辑' : '新增'));

      const flowMacroGetFontAwesomeList = ref<Recordable[]>([]);
      //获取所有图标
      const getFlowMacroGetFontAwesomeData = async () => {
        flowMacroGetFontAwesomeList.value = [];
        const data = (await getFlowMacroGetFontAwesome()) || [];
        if (isArray(data)) {
          data.forEach((item) => {
            flowMacroGetFontAwesomeList.value.push({
              value: item,
              label: item,
            });
          });
        }
      };
      onMounted(() => {
        getFlowMacroGetFontAwesomeData();
      });
      const formGetFieldsData = ref([]);
      //获取数据
      const getFormGetFieldsData = () => {
        formGetFieldsData.value = [];
        try {
          if (!formCode.value) return;
          getFormGetFields({ formCode: formCode.value }).then((res) => {
            formGetFieldsData.value = res || [];
            formGetFieldsData.value.forEach((item: Recordable) => {
              delete item.options;
              item.value = item.name;
              item.label = item.title;
            });
          });
        } catch (err) {
          console.error('getFormGetFields', err);
        }
      };
      const handleFieldName = (_, node) => {
        dataRef.value.innerHtml = node.label;
      };

      const formGetBtnsData: any = ref([]);
      const getFormGetBtnsData = () => {
        formGetBtnsData.value = [];
        try {
          if (!moduleCode.value) return;
          getVisualListColOperateCustomBtns({ moduleCode: moduleCode.value }).then((res) => {
            formGetBtnsData.value = res || [];
            formGetBtnsData.value.forEach((item: Recordable) => {
              delete item.options;
              item.value = item.name;
              item.label = item.title;
            });
            console.log('formGetBtnsData', formGetBtnsData.value);
          });
        } catch (err) {
          console.error('getVisualListColOperateCustomBtns', err);
        }
      };
      const handleBtnName = (_, node) => {
        dataRef.value.innerHtml = node.label;
      };

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });

          const values = await validate();
          const formInfo = Object.assign({}, dataRef.value, values);
          formInfo.field = formInfo.fieldName ? formInfo.fieldName : '';
          console.log('dataRef.value', dataRef.value);
          console.log('formInfo', formInfo);

          let imgs = {};
          if (fileList.value && fileList.value.length) {
            imgs[`bgImg_${formInfo.x}_${formInfo.y}`] = fileList.value[0];
          }
          createMessage.success('操作成功');
          const obj = layoutList.value[currentItemIndex.value];
          if (obj) {
            Object.assign(obj.record, formInfo);
            console.log('obj', obj);
            layoutList.value[currentItemIndex.value] = { ...obj };
          }
          const data = setData(layoutList.value, column.value);
          const formData = {
            ...formInfo,
            ...imgs,
            moduleCode: moduleCode.value,
            widgets: JSON.stringify(data),
          };
          delete formData.bgColor;
          delete formData.fontColor;
          let form = new FormData();
          for (let v in formData) {
            const value = formData[v] == null || formData[v] == undefined ? '' : formData[v];
            form.append(v, value);
          }
          if (type.value === 'pc') {
            await getVisualUpdatePageList(form);
          } else if (type.value === 'phone') {
            await getVisualUpdatePageMobileList(form);
          }
          closeModal();
          emit('success');
        } catch (err) {
          console.error(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      //上传前校验
      const beforeUpload: UploadProps['beforeUpload'] = (file) => {
        fileList.value = [file];
        return false;
      };
      //上传change
      const handleChange = (e) => {
        console.log('e', e);
      };
      // 上传文件删除
      const handleRemove: UploadProps['onRemove'] = (file) => {
        const index = fileList.value!.indexOf(file);
        const newFileList = fileList.value!.slice();
        newFileList.splice(index, 1);
        fileList.value = newFileList;
      };
      const filterOption = (input: string, option: any) => {
        return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      };
      return {
        registerModal,
        getTitle,
        handleSubmit,
        registerForm,
        dataRef,
        typeOptions,
        formGetFieldsData,
        handleFieldName,
        alignOptions,
        fileList,
        beforeUpload,
        handleChange,
        handleRemove,
        filterOption,
        flowMacroGetFontAwesomeList,
        serverInfo,
        formGetBtnsData,
        handleBtnName,
      };
    },
  });
</script>
<style lang="less" scoped>
  :deep(.ant-image) {
    display: flex;
    align-items: center;
  }
</style>
